// ES6 ES2015
// promise 状态
const PROMISE_STATUS_PENDING = 'pending'
const PROMISE_STATUS_FULFILLED = 'fulfilled'
const PROMISE_STATUS_REJECTED = 'rejected'

class YZPromise {
  constructor(executor) {
    this.status = PROMISE_STATUS_PENDING
    this.value = undefined
    this.reason = undefined

    const resolve = (value) => {
      if(this.status === PROMISE_STATUS_PENDING) {
        queueMicrotask(() => {
          this.status = PROMISE_STATUS_FULFILLED
          console.log("resolve被调用");
          this.value = value
          this.onFulfilled()
        })
        // setTimeout(() => {
        //   this.status = PROMISE_STATUS_FULFILLED
        //   console.log("resolve被调用");
        //   this.value = value
        //   this.onFulfilled()
        // }, 0)
      }
    }
    const reject = (reason) => {
      if(this.status === PROMISE_STATUS_PENDING) {
        this.status = PROMISE_STATUS_REJECTED
        console.log("reject被调用");
        this.reason = reason
      }
    }
    executor(resolve, reject)
  }

  then(onFulfilled, onRejected) {
    this.onFulfilled = onFulfilled
    this.onRejected = onRejected
  }

}

const promise = new YZPromise((resolve, reject) => {
  console.log("状态pending");
  resolve(22222)
  // reject(11111)
}).then(res => {
  console.log("res", res);
})